let homepageBusiness = module.exports = {};


const Promise = require('bluebird');
const crypto = require('crypto');
const config = require('config');
const errinfo = require('../errinfo');
const responseJsonUtils = require('../utils/responseJsonUtils');

// access wechat
homepageBusiness.accessWechat = function (req, res, next) {
    let encodeText = makeSignature(req);

    if (req.query.signature !== encodeText) {
        next(responseJsonUtils.json(errinfo.wechat.messageCheckFailure));
        return;
    }

    res.status(200).send(req.query.echostr || '').end();
};

function makeSignature(req) {
    if (!req.query.timestamp || !req.query.nonce || !req.query.signature) {
        return null;
    }
    // console.log(req.query.timestamp, req.query.nonce, req.query.signature);
    let sha1 = crypto.createHash('sha1');
    let array = [config.wechat.token, req.query.timestamp, req.query.nonce];
    array.sort();
    let clearText = array.toString().replace(/,/g, '');
    sha1.update(clearText, 'utf-8');
    return sha1.digest('hex');
}


